package day9;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author oldliu
 * @since 1.0
 */
public class AdvanceTalkServer {
    public static void main(String[] args) {
        ServerSocket st = null;
        try {
            st = new ServerSocket(9999);
            System.out.println("listen on 9999端口");
            while (true) {
                final Socket s = st.accept();
                //new SocketThread(s).start();
                new ObjectSenderThread(s).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
class SocketThread extends Thread{
    private Socket s;
    public SocketThread(Socket s){
        this.s=s;
    }
    @Override
    public void run() {
        System.out.println(s + "链接了。。。");
        System.out.println(s.getInetAddress()+":"+s.getPort()+","+s.getLocalPort());
        try {
            InputStream in = s.getInputStream();
            OutputStream out = s.getOutputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            PrintWriter pw = new PrintWriter(out, true);
            String msg = null;
            while ((msg = br.readLine()) != null) {
                System.out.println("客户端说:" + msg);
                pw.println("你说的：" + msg + " 朕知道了。。。");
                if (msg.equals("exit"))
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(s!=null&&s.isClosed()==false) {
                try {
                    System.out.println(s+"退出了。。。");
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}